<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content plan-detail">
      <div v-if="TYPE_ENUM.DETAIL.includes($route.query.type)" class="fixed-explain">
        <e-heading grade='1'>设置训练计划模板</e-heading>
        <span class="form-help">在本页调整训练计划，确认无误后点击“提交”按钮即可</span>
      </div> 
      <div v-else>     
        <e-heading grade='1'>训练计划 —— {{planName}}</e-heading>
      </div>
      <div class="plan-introduce">
        <div>
          <span>训练名称：{{planName}}</span>
        </div>
        <div class="is-detail-plan"><span>训练方式：</span></div>
      </div>

      <!-- 训练计划列表 -->
      <plan-list 
        :data="datalist"
        @up="handleUp"
        @down="handleDown"
        @detail="handleDetail"
        @delete="handleDelete"/>

      <!-- 操作 -->
      <div class="button-box" v-if="!pageLoading">
        <el-button :type="$route.query.type == TYPE_ENUM.PREVIEW ? 'primary' : 'normal'" @click="handleCancel">返 回</el-button>
        <!-- 新增或者编辑详情按钮操作 -->
        <el-button type="primary" @click="handleSuccess" v-if="[TYPE_ENUM.DETAIL, TYPE_ENUM.EDIT].includes($route.query.type)" :disabled="datalist.length == 0" :loading="loading">提 交</el-button>
        <!-- 待审核状态详情的按钮操作 -->
        <el-button type="primary" @click="handleDeny" v-if="$route.query.status == 0 && roleType != 99" :loading="loading">拒 绝</el-button>
        <el-button type="primary" @click="handlePass" v-if="$route.query.status == 0 && roleType != 99" :loading="loading">通 过</el-button>
        <!-- 未通过详情的按钮操作 -->
        <el-button type="primary" @click="handleEdit" v-if="$route.query.status == 1">编 辑</el-button>
        <el-button type="primary" @click="handleRemoveTemp" v-if="$route.query.status == 1" :loading="loading">删 除</el-button>
        <el-button type="primary" @click="handleAgainsubmit" v-if="$route.query.status == 1" :loading="loading" :disabled="datalist.length == 0">再次提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import api from 'api/trainingProgram'
import { TYPE_ENUM } from './constant'
import { mapGetters } from 'vuex'
import PlanList from './components/PlanList'
import validator from 'utils/validator'

export default {
  components: {
    PlanList
  },
  computed: {
    ...mapGetters({
      pageLoading: 'loading'
    }),
    _initData () {
      return this.$store.getters.temporary_detail_data
    }
  },
  data () {
    return {
      TYPE_ENUM,
      validator,
      loading: false,
      sortable: null,
      planName: '',
      datalist: [],
      isEdit: '', // 是否是编辑
      trainInfoId: '',
      selectedId: [],
      roleType: ''
    }
  },
  destroyed () {
    window.onbeforeunload = null
  },
  watch: {
    _initData (newVal, oldVal) {
      this.planName = newVal.topic
      this.datalist = newVal.selectedList || []
      this.isEdit = newVal.type
    },
    '$route.query.type' (newVal) {
      if (newVal === TYPE_ENUM.DETAIL) {
        this.setSort()
      }
    }
  },
  mounted () {
    this.roleType = localStorage.getItem('role_type') - 0
    if ([TYPE_ENUM.DETAIL, TYPE_ENUM.PREVIEW].includes(this.$route.query.type)) {
      this.planName = this._initData.topic
      this.datalist = this._initData.selectedList || []
      this.isEdit = this._initData.type
      if (this.$route.query.type === TYPE_ENUM.DETAIL) {
        this.setSort()
        this.closeBrowser()
      }
    } else {
      api.getSingleTemp({id: this.$route.query.id}).then(res => { // 查看单个训练计划详情
        this.datalist = res.data
        this.planName = res.data[0].topic
      })
    }
  },
  methods: {
    handleDetail (row) { // 详情
      this.$router.push({path: '/training/trainingprogram/mode/show', query: {id: row.id}})
    },
    handleCancel () {
      history.back()
    },
    handleUp (index) { // 上移
      if (this.datalist.length > 1 && index !== 0) {
        this.datalist = this.swapItems(this.datalist, index, index - 1)
      }
    },
    handleDown (index) { // 下移
      if (this.datalist.length > 1 && index !== (this.datalist.length - 1)) {
        this.datalist = this.swapItems(this.datalist, index, index + 1)
      }
    },
    swapItems (arr, index1, index2) { // 替换
      arr[index1] = arr.splice(index2, 1, arr[index1])[0]
      return arr
    },
    setSort () { // 拖拽排序
      const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        onEnd: ev => {
          let [currentIndex, draggableIndex] = [ev.oldIndex, ev.newIndex]
          let [h, q] = [this.datalist[draggableIndex], this.datalist[currentIndex]]
          if (currentIndex < draggableIndex) { // 下移动
            if (draggableIndex > currentIndex + 1) {
              for (let j = currentIndex; j < draggableIndex; j++) {
                this.datalist[j] = this.datalist[j + 1]
              }
              this.datalist[draggableIndex] = q
            } else {
              this.datalist[draggableIndex] = q
              this.datalist[currentIndex] = h
            }
          } else { // 上移动
            if (draggableIndex < currentIndex - draggableIndex) {
              for (let j = currentIndex; j > draggableIndex; j--) {
                this.datalist[j] = this.datalist[j - 1]
              }
              this.datalist[draggableIndex] = q
            } else {
              this.datalist[draggableIndex] = q
              this.datalist[currentIndex] = h
            }
          }
        }
      })
    },
    handleDelete (index) {
      this.$confirm('确定移除该训练计划吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.datalist.splice(index, 1)
      }).catch(() => {})
    },
    closeBrowser () { // 是否关闭当前网页提示
      window.onbeforeunload = () => {
        return false
      }
    },
    handlePass () { // 通过
      api.checkPlanTemp({id: this.$route.query.id, auditStatus: 2}, {context: this, successMsg: '审核通过'}).then(() => {
        this.$router.push({path: '/training/trainingprogram/plan', query: {authStatus: '2'}})
      })
    },
    handleDeny () { // 拒绝
      api.checkPlanTemp({id: this.$route.query.id, auditStatus: 1}, {context: this, successMsg: '审核未通过'}).then(() => {
        this.$router.push({path: '/training/trainingprogram/plan', query: {authStatus: '1'}})
      })
    },
    handleAgainsubmit () { // 再次提交
      api.checkPlanTemp({id: this.$route.query.id, auditStatus: this.roleType !== 99 ? 2 : 0, checkAgain: new Date().getTime()}, {context: this, successMsg: '再次提交成功'}).then(() => {
        this.$router.push({path: '/training/trainingprogram/plan', query: {authStatus: this.roleType !== 99 ? '2' : '0'}})
      })
    },
    handleEdit () { // 编辑
      this.$router.push({name: 'planTemplate', query: {trainPlanId: this.$route.query.id, type: TYPE_ENUM.EDIT}})
    },
    handleRemoveTemp () { // 删除
      api.getDeleteBef({trainPlanId: this.$route.query.id}, {context: this, errorMsg: 'none'}).then(res => {
        this.$msgbox({
          title: '温馨提示',
          message: <div>
            <div>确定删除该模板吗？</div>
            <div style="margin-top: 10px">删除后将不可恢复</div>
          </div>,
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          showCancelButton: true,
          type: 'warning'
        }).then(res => {
          api.deletePlan({id: this.$route.query.id}, {context: event.target, successMsg: '删除成功'}).then(res => {
            this.fetch(this.query)
          })
        }).catch(() => {})
      }).catch(err => {
        this.$confirm(err.msg, '温馨提示', {
          confirmButtonText: '我知道了',
          showCancelButton: false,
          type: 'warning'
        }).catch(() => {})
      })
    },
    handleSuccess () {
      this.selectedId = []
      this.datalist.forEach(item => {
        return this.selectedId.push(item.id)
      })
      if (this.isEdit === TYPE_ENUM.EDIT || this.$route.query.type === TYPE_ENUM.EDIT) {
        api.editPlanTemp({
          topic: this.planName,
          trainStyleId: this.selectedId,
          trainInfoId: this.$route.query.id
        }, {context: this, successMsg: '修改模板成功'}).then(res => {
          this.$router.push({path: '/training/trainingprogram/plan', query: {authStatus: this.roleType !== 99 ? '2' : '0'}})
        })
      } else {
        api.addPlanTemplate({
          topic: this.planName,
          trainStyleId: this.selectedId
        }, {context: this, successMsg: '新增模板成功'}).then(res => {
          this.$router.push({path: '/training/trainingprogram/plan', query: {authStatus: this.roleType !== 99 ? '2' : '0'}})
        })
      }
    }
  }
}
</script>

<style lang="scss">
  .plan-detail {
    .fixed-explain {
      position: relative;
      .form-help {
        position: absolute;
        top: 30px;
        left: 0px;
      }
    }
    .plan-introduce {
      margin-top: 50px;
      .plan-methods {
        padding: 0px 18px 20px;
      }
      .is-detail-plan {
        padding: 20px 0;
      }
    }
    .el-button {
      margin: 5px
    }
  }
</style>
